package br.sales.view.listener;

import java.util.Locale;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.primefaces.util.ArrayUtils;

import br.sales.entity.UserEntity;
import br.sales.view.bean.MainBean;
import br.sales.view.util.ViewUtil;


public class AppPhaseListener implements PhaseListener{

	private static final long serialVersionUID = -8304543755500723756L;
	private String[] pages = {"configurations.xhtml"};
	
	@Override
	public void afterPhase(PhaseEvent event) {
		System.out.println("AFTER PHASE");
		MainBean mainBean = (MainBean) ViewUtil.getManagedBean(event.getFacesContext(), "mainBean", MainBean.class);
		setLocale(mainBean.getLoggedUser());
	}

	private boolean requireAuthorization(String currentPage) {
		return ArrayUtils.contains(pages, currentPage);
	}

	@Override
	public void beforePhase(PhaseEvent event) {
		System.out.println("BEFORE PHASE");
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}
	
	private void setLocale(UserEntity userEntity){
		if (userEntity != null && userEntity.getLanguage() != null){
			FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(userEntity.getLanguage().getKey(), userEntity.getLanguage().getCountry()));
		} 
	}

}
